import React, { useState, useEffect } from 'react'
import { Table, Button, message, Space, Tag } from 'antd'
import api from '../api'
import { scanQRCodePay } from '../helpers'
import { ORDER_STATUS } from '../constants'
function Orders() {
  const [orders, setOrders] = useState([])
  const fetchOrders = () => {
    api.get('/api/orders')
      .then(response => {
        setOrders(response.data)
      })
      .catch(error => {
        console.error('获取订单失败:', error)
        message.error('获取订单失败')
      })
  }
  useEffect(fetchOrders, [])
  const closeOrder = orderNo => {
    api.get(`/api/payment/order/${orderNo}/close`)
      .then(() => {
        fetchOrders()
        message.success('订单关闭成功')
      }, (error) => {
        console.error('订单关闭失败:', error)
        message.error('订单关闭失败')
      })
  }
  const columns = [
    { title: '订单号', dataIndex: 'id', key: 'id' },
    { title: '产品', dataIndex: 'product', key: 'product', render: product => product?.name },
    { title: '总费用', dataIndex: 'totalFee', key: 'totalFee', render: val => <span>￥{(val / 100).toFixed(2) }</span> },
    { title: '状态', dataIndex: 'orderStatus', key: 'orderStatus',
      render: text => {
        switch(text) {
          case ORDER_STATUS.PAID: return <Tag color={'green'}>支付成功</Tag>;
          case ORDER_STATUS.UN_PAID: return <Tag color={'orange'}>未支付</Tag>;
          case ORDER_STATUS.CLOSE: return <Tag color='red'>已关闭</Tag>;
          default: return <Tag>{text}</Tag>
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        if (record.orderStatus === ORDER_STATUS.UN_PAID) {
          return (
            <Space>
              <Button 
                type="primary"
                size='small'
                onClick={() => scanQRCodePay({ orderNo: record.id, code_url: record.code_url, callback: fetchOrders })}>继续支付</Button>
              <Button
                danger
                size='small'
                onClick={() => closeOrder(record.id) }>关闭订单</Button>
            </Space>
          )
        } else {
          return null
        }
      }
    }
  ]
  return (
    <div style={{ padding: 24 }}>
      <Table columns={ columns } dataSource={ orders } rowKey="id" />
    </div>
  )
}

export default Orders
